import { queryOssSignature } from '@/api/common';
import { useStore } from '@/store/index';
import { showLoading, hideLoading, showToast } from "./toast";
import moment from "moment";

/**
 * 将base64图片转为可识别的临时图片
 * @param {String } base64Data base64格式的图片数据
 * @returns 图片临时地址
 */
export function base64ToTempPath(base64Data) {
  let fs = uni.getFileSystemManager();
  // 格式化base64数据
  base64Data = base64Data.replace(
    /^data:image\/\w+;base64,/,
    ""
  );
  // 组装临时路径
  let tempPath =
    wx.env.USER_DATA_PATH +
    `/realName-authentication-qrCode-${moment().unix()}.png`;
  // 写入文件
  fs.writeFileSync(tempPath, base64Data, 'base64');
  return tempPath;
}

/**
 * 保存图片到相册
 * @param {String} tempPath 图片临时路径
 */
export function saveImage(tempPath) {
  showLoading("加载中");

  return new Promise(resolve => {
    uni.saveImageToPhotosAlbum({
      filePath: tempPath,
      success() {
        resolve()
        showToast("图片已保存至相册");
      },
      fail() {
        showToast("保存失败，请稍后重试");
      },
      complete() {
        hideLoading();
      },
    });
  })
}

/**
 * 获取oss配置
 * @param {String} 类型（如代理、门店）
 */
export function getOssSignature(moduleType) {
  return new Promise((resolve) => {
    queryOssSignature({
      params: {
        _action: 'signature',
        dir: `app/merchant/${moduleType}/`
      }
    }).then(res => {
      resolve(res.payload);
    });
  });
}

/**
 * 上传图片
 * @param {Object} ossConfig oss签名配置
 */
export function uploadImg(ossConfig, sourceType) {
  let tempSourceType = sourceType ? sourceType : ['album', 'camera'];

  return new Promise((resolve) => {
    uni.chooseImage({
      count: 1,
      sizeType: ["original"],
      sourceType: tempSourceType,
      success: (chooseImageRes) => {
        const store = useStore();
        const userId = store.userInfo.userId;
        const tempFilePaths = chooseImageRes.tempFilePaths;
        const tempFiles = chooseImageRes.tempFiles;
        const aliYunFileKey = `${ossConfig.dir}${userId}/${new Date().getTime()}.png`;

        let maxSize = 1024 * 1024 * 5;
        let imageTypePass = tempFiles.some(item => {
          return ['.jpg', '.png', '.bmp', '.jif'].some(type => {
            return item.path.endsWith(type);
          });
        });

        if (!imageTypePass) {
          // 请上传正确格式的图片(png、jpg、bmp、jif)
          showModal({ content: '请上传正确格式的图片(png、jpg、bmp、jif)' });
          return;
        }

        if (tempFiles[0].size > maxSize) {
          // 无法上传大于10M的图片
          showModal({ content: '无法上传大于5M的图片' });
          return;
        };

        showLoading("上传中");

        uni.uploadFile({
          url: ossConfig.host,
          filePath: tempFilePaths[0],
          formData: {
            key: aliYunFileKey,
            policy: ossConfig.policy,
            OSSAccessKeyId: ossConfig.accessid,
            signature: ossConfig.signature,
            success_action_status: "200",
          },
          name: "file",
          success() {
            resolve(ossConfig.host + "/" + aliYunFileKey);
          },
          fail() {
            uni.showModal({
              title: "提示",
              content: "上传失败，请检查网络",
              success: function (res) {
                if (res.confirm) {
                  uploadImg();
                }
              },
            });
          },
          complete() {
            hideLoading();
          },
        });
      },
    });
  });
}
